package com.lagou.rpc.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;

/**
 * @ClassName RpcClientHandler
 * @Description
 * @Author playboy
 * @Date 2021/6/5 4:05 下午
 * @Version 1.0
 **/
@Component
@ChannelHandler.Sharable
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable<String> {

	private ChannelHandlerContext context;

	private String requestMsg;

	private String responseMsg;

	public void setRequestMsg(String requestMsg) {
		this.requestMsg = requestMsg;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		context = ctx;
	}

	@Override
	protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
		responseMsg = s;
		notify();
	}


	@Override
	public synchronized String call() throws Exception {
		context.writeAndFlush(requestMsg);
		wait();
		return responseMsg;
	}
}
